package com.roncoo.education.course.service.api.auth.biz;

import com.roncoo.education.course.common.req.CourseVideoMemoryREQ;
import com.roncoo.education.course.service.dao.CoursePeriodDao;
import com.roncoo.education.course.service.dao.impl.mapper.entity.CoursePeriodMemory;
import com.roncoo.education.util.base.Result;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * 课时视频进度
 */
@Component
public class AuthApiCourseVideoPeriodMemoryBiz {

    @Autowired
    private CoursePeriodDao coursePeriodDao;

    @Autowired
    private AuthApiCourseComponent authApiCourseComponent;

    public CoursePeriodMemory getByVideoNoAndUserNo(Long videoNo,Long userNo){
        return coursePeriodDao.getByVideoNoAndUserNo(videoNo,userNo);
    }

    public int updateById(CoursePeriodMemory coursePeriodMemory){
        return coursePeriodDao.updateById(coursePeriodMemory);
    }

    public int save(CoursePeriodMemory coursePeriodMemory){
        return coursePeriodDao.save(coursePeriodMemory);
    }

    /**
     *
     * @param req
     * @param userNo
     * @return
     */
    public Result<CoursePeriodMemory> updateUserVideoMemory(CourseVideoMemoryREQ req,Long userNo){
        //检查
        Result check = authApiCourseComponent.check(req.getCourseId(), req.getChapterId(), req.getPeriodId());
        if(check!=null){
            return check;
        }

        //如果没有播放进度记录，新增
        CoursePeriodMemory byVideoNoAndUserNo = getByVideoNoAndUserNo(req.getVideoNo(), userNo);
        if(byVideoNoAndUserNo == null){
            byVideoNoAndUserNo = new CoursePeriodMemory();
            BeanUtils.copyProperties(req,byVideoNoAndUserNo);
            int save = save(byVideoNoAndUserNo);
            if(save>0){
                return Result.success(byVideoNoAndUserNo);
            }
            return Result.error("新增播放记录失败");//失败前端就不用理会了
        }

        //如果已有播放进度记录，更新
        byVideoNoAndUserNo.setLastMemory(req.getLastMemory());
        byVideoNoAndUserNo.setIsFinish(req.getIsFinish());
        int i = updateById(byVideoNoAndUserNo);
        if(i>0){
            return Result.success(byVideoNoAndUserNo);
        }
        return Result.error("更新播放记录失败");//失败前端就不用理会了
    }
}
